#pragma once
#include "Sock.hpp"

static void service(int sock, const std::string& ip, const uint16_t& port)
{
    char buffer[1024];
    while (1)
    {
        memset(buffer, 0, sizeof(buffer));
        ssize_t s = read(sock, buffer, sizeof(buffer) - 1);
        if (s > 0)
        {
            buffer[s] = 0;
            std::cout << ip << ": " << port << "# " << buffer << std::endl;
            write(sock, buffer, strlen(buffer));
        }
        else if (s == 0)
        {
            logMessage(NORMAL, "%s: %d shutdown, me too!", ip.c_str(), port);
            break;
        }
        else
        {
            logMessage(ERROR, "Read socket error, %d: %s", errno, strerror(errno));
            break;
        }
    }
    close(sock);
}

class TcpServer
{
public:
    TcpServer(uint16_t port, std::string ip = "0.0.0.0")
        :_port(port)
        ,_ip(ip)
        ,_listensock(-1)
    {
        // 1.创建套接字
        _listensock = Sock::Socket();

        // 2.bind
        Sock::Bind(_listensock, _port);

        // 3.listen
        Sock::Listen(_listensock);
    }

    void start()
    {
        // 4.获取连接
        uint16_t client_port;
        std::string client_ip;
        int servicesock = Sock::Accept(_listensock, &client_port, &client_ip);
        // Sock::SetNonBloack(servicesock); // 设置非阻塞

        // 业务处理
        service(servicesock, client_ip, client_port);
    }

    ~TcpServer()
    {
        if (_listensock > 0)
            close(_listensock);
    }

private:
    uint16_t _port;
    std::string _ip;
    int _listensock;
};
